<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>LangChain 聊天机器人（流式）</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; }
    #chat { border: 1px solid #ccc; padding: 10px; height: 400px; overflow-y: scroll; }
    .user { color: blue; margin: 5px 0; }
    .bot { color: green; margin: 5px 0; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h2>🤖 LangChain 聊天机器人（流式输出）</h2>
  <div id="chat"></div>
  <input type="text" id="message" placeholder="请输入内容..." style="width:80%">
  <button onclick="sendMessage()">发送</button>

  <script>
    function sendMessage() {
      const input = document.getElementById("message");
      const chatBox = document.getElementById("chat");
      const userMessage = input.value.trim();
      if (!userMessage) return;

      chatBox.innerHTML += `<div class="user">你: ${userMessage}</div>`;
      const botDiv = document.createElement("div");
      botDiv.className = "bot";
      botDiv.innerText = "机器人: ";
      chatBox.appendChild(botDiv);
      chatBox.scrollTop = chatBox.scrollHeight;

      input.value = "";

      fetch("/chat_stream", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: userMessage })
      }).then(res => {
        const reader = res.body.getReader();
        const decoder = new TextDecoder("utf-8");

        function read() {
          reader.read().then(({ done, value }) => {
            if (done) return;
            const text = decoder.decode(value);
            text.split("\n\n").forEach(line => {
              if (line.startsWith("data: ")) {
                botDiv.innerText += line.replace("data: ", "");
                chatBox.scrollTop = chatBox.scrollHeight;
              }
            });
            read();
          });
        }
        read();
      });
    }
  </script>
</body>
</html>
